<template>
  <div class="user-box">
    <header class="header">
      <el-button type="primary" key="btn" @click="addUser">新增</el-button>
    </header>
    <div class="content">
      <el-table :data="listArr">
        <el-table-column v-for="item in tableHeader" :prop="item.type" :label="item.label" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link size="small" @click.prevent="detailRow(scope.row)">
              详情
            </el-button>
            <el-button @click.prevent="deleteRow(scope.$index)" type="danger" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增和详情 -->
    <add :dialogTableVisible="dialogTableVisible" title="新增" :show="show" @handle="handle">
      <el-form :model="formData" :rules="ruleForm" ref="formDom" label-width="60px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="formData.age" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio label="男" />
                <el-radio label="女" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </add>
  </div>
</template>

<script setup lang="ts">
import Add from './add.vue'
import { ref, reactive, unref, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 列表数据
const listArr = reactive([
  { name: '张三', age: 20, sex: '男', address: '四川省成都市' },
  { name: '李四', age: 21, sex: '男', address: '四川省成都市' },
])
const tableHeader = [
  { type: 'name', label: '姓名' },
  { type: 'age', label: '年龄' },
  { type: 'sex', label: '性别' },
  { type: 'address', label: '地址' },
]


// 删除
function deleteRow(index: any) {
  ElMessageBox.confirm(
    '是否删除?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      listArr.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

// 新增
let dialogTableVisible = ref(false)
function addUser() {
  dialogTableVisible.value = true
  show.value = true
}
const formData = reactive({
  name: '',
  age: 0,
  sex: '',
  address: ''
})
// 数据验证
const ruleForm = reactive({
  name: [
    { required: true, message: '请输入名字', trigger: ['blur', 'change'] },
    { min: 2, max: 5, message: '名字至少2-5位', trigger: ['blur', 'change'] },
  ],
  age: [
    // min: 0, max: 200, 
    { required: true, message: '年龄范围0-200', trigger: ['blur', 'change'] },
  ],
  address: [
    { required: true, message: '请输入地址', trigger: ['blur', 'change'] },
  ],
})
const formDom = ref()
// 清空表单验证规则提示
function reset() {
  const form = unref(formDom)
  form.resetFields()
  clearTheObj(formData) // 清除数据
}
// 弹窗事件
function handle(type: any) {
  if (type === 'close') {
    dialogTableVisible.value = false
    reset()
    return
  }
  formDom.value.validate((valid: any) => {
    if (valid) {
      // 因为formData是响应式的，直接添加得到话会删除原来存在的数据
      // 所以使用 ...这个
      listArr.unshift({ ...formData })
      dialogTableVisible.value = false
      ElMessage({
        message: '新增成功',
        type: 'success',
      })
      reset()
    }
  })
}
// 将数据清空
const clearTheObj = (obj: any) => {
  let emptyArr = {};
  for (let key in obj) {
    emptyArr[key] = '';
  }
  Object.assign(obj, emptyArr)
}

// 详情
const show = ref(true)
function detailRow(data: any) {
  dialogTableVisible.value = true
  const form = toRaw(data) // 转化为普通对象
  Object.assign(formData, form) // 赋值
  show.value = false
}
</script>

<style lang="scss" scoped>
.user-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 10px;

  .content {
    flex: 1;
  }
}
</style>